package com.yoomiito.app.ui.search

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import butterknife.BindView
import butterknife.OnClick
import cn.droidlover.xdroidmvp.cache.SharedPref
import cn.droidlover.xdroidmvp.router.Router
import com.yoomiito.app.Constant
import com.yoomiito.app.R
import com.yoomiito.app.base.App
import com.yoomiito.app.base.BaseActivity
import com.yoomiito.app.model.bean.GoodsInfo
import com.yoomiito.app.model.bean.VideoInfo
import com.yoomiito.app.model.home.HotSearch
import com.yoomiito.app.model.home.TaoBaoHotSearch
import com.yoomiito.app.ui.video.VideoPlayActivity
import com.yoomiito.app.utils.CacheUtils
import com.yoomiito.app.utils.EditTextUtil
import com.yoomiito.app.utils.L
import com.yoomiito.app.utils.video.MediaPlayerVideoInfo
import com.yoomiito.app.utils.video.MetadataRetrieverVideoInfo
import com.yoomiito.app.utils.video.VideoInfoUtil
import com.zhy.view.flowlayout.FlowLayout
import com.zhy.view.flowlayout.TagAdapter
import com.zhy.view.flowlayout.TagFlowLayout
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.act_search.*
import kotlinx.android.synthetic.main.item_search.*
import kotlinx.android.synthetic.main.item_search_toolbar.*
import java.util.*

class SearchActivity : BaseActivity<SearchPresenter>() {

    private var serachList: MutableList<String>? = null
    private var tagAdapter: TagAdapter<String>? = null
    private var key: String? = null
    private lateinit var videoInfo:VideoInfo
    private var hotSearchData:List<HotSearch>?=null
    override fun getLayoutId(): Int = R.layout.act_search

    override fun newP(): SearchPresenter = SearchPresenter(App.mAppConfig)

    override fun initData(savedInstanceState: Bundle?) {
        act_search_back.setOnClickListener { finish() }
        act_search_search.setOnClickListener {
            val s = item_search_et.text.toString().trim { it <= ' ' }
            if (TextUtils.isEmpty(s)) {
                showToast("请输入搜索内容")
                return@setOnClickListener
            }
            putCache(s)
            key = s
            toResult()
        }
        act_search_del.setOnClickListener {
            SharedPref.getInstance(App.getInstance()).remove(Constant.HISTORY)
            serachList!!.clear()
            tagAdapter!!.notifyDataChanged()
            act_search_history.visibility = View.GONE
        }
        item_search_del.setOnClickListener {
            item_search_et.setText("")
        }
        videoCourse.setOnClickListener {
            VideoPlayActivity.start(this, videoInfo!!)
        }

    }
    override fun onResume() {
        super.onResume()
        p?.getHotSearch()
//        serachList = SharedPref.getInstance(App.getInstance()).getListData(Constant.HISTORY, String::class.java)
        serachList = CacheUtils.getTaoBaoSearchHistory()
//        if (serachList == null) {
//            serachList = ArrayList()
//        }
        act_search_history.visibility = if (serachList?.size==0) View.GONE else View.VISIBLE
        tagAdapter = object :TagAdapter<String>(serachList){
            override fun getView(parent: FlowLayout?, position: Int, t: String?): View {
                val tv = LayoutInflater.from(this@SearchActivity).inflate(R.layout.item_tv, parent, false) as TextView
                tv.text = t
                return tv
            }

        }
        historySearchFlowLayout.adapter = tagAdapter
        historySearchFlowLayout.setOnTagClickListener { view: View?, position: Int, parent: FlowLayout? ->
            key = serachList!![position]
            item_search_et.setText(key)
            toResult()
            false
        }
        hotSearchFlowLayout.setOnTagClickListener { view: View?, position: Int, parent: FlowLayout? ->
            key = hotSearchData?.get(position)?.keyword
            item_search_et.setText(key)
            putCache(key!!)
            toResult()
            false
        }
    }

    fun setHotSearch(data:TaoBaoHotSearch?){
        if (data!=null){
            if (!data.video?.isNullOrEmpty()){
                Observable.just<String>(data.video)
                        .observeOn(Schedulers.io())
                        .map { s ->
                            var videoInfoUtil: VideoInfoUtil
                            try {
                                videoInfoUtil = MetadataRetrieverVideoInfo(s)//在vivo手机 系统6.1上会崩溃 这时候就使用MediaPlayerVideoInfo
                            } catch (e: Exception) {
                                videoInfoUtil = MediaPlayerVideoInfo(s)
                            }

                            val videoInfo = VideoInfo()
                            videoInfo.width = videoInfoUtil.getVideoWidth()
                            videoInfo.height = videoInfoUtil.getVideoHeight()
                            videoInfo.url = s
                            videoInfoUtil.release()
                            videoInfo
                        }
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe { s ->
                            videoInfo = s
                            videoCourse.visibility = View.VISIBLE
                        }
            }
            if (data.hot_search!=null){
                hotSearchData = data.hot_search
                hotSearch.visibility = if(data.hot_search.isEmpty()) View.GONE else View.VISIBLE
                hotSearchFlowLayout.adapter =  object :TagAdapter<HotSearch>(data.hot_search){
                    override fun getView(parent: FlowLayout?, position: Int, t: HotSearch?): View {
                        val tv = LayoutInflater.from(this@SearchActivity).inflate(R.layout.item_tv, parent, false) as TextView
                        tv.text = t?.keyword
                        return tv
                    }

                }
            }
        }
    }

    fun toResult() {
        Router.newIntent(this)
                .to(SearchResultActivity::class.java)
                .putString(Constant.KEY, key)
                .launch()
    }

    private fun putCache(str:String){
//        if (!serachList?.contains(str)!!) {
//            if (serachList?.size!! >= 5) {
//                serachList?.removeAt((serachList?.size!!-1))
//            }
//            serachList?.add(0, str)
//            SharedPref.getInstance(App.getInstance()).putListData(Constant.HISTORY, serachList)
//        }
        CacheUtils.saveTaoBaoSearchHistory(str)
    }
}